import React, { useState, useEffect } from 'react';
import { Table, Image, Switch } from 'antd';
import { showData, updateFlag } from '../../api/product';

function Index() {
  const [proList, setProList] = useState([]);

  useEffect(() => {
    // 请求的是 被推荐的数据
    showData({ type: 'isrecommend', flag: 1 }).then((res) => {
      setProList(res.data.data);
    });
  }, []);

  const changeRecommendFlag = (proid, text) => {
    updateFlag({ proid, type: 'isrecommend', flag: text === 1 ? false : true }).then(() => {
      // 重新请求数据
      showData({ type: 'isrecommend', flag: 1 }).then((res) => {
        setProList(res.data.data);
      });
    });
  };

  // 删除了排序以及筛选，只保留 推荐列表的状态
  const columns = [
    { title: '序号', width: 100, fixed: 'left', render: (text, record, index) => <span>{index + 1}</span> },
    { title: '名称', width: 260, fixed: 'left', dataIndex: 'proname' },
    { title: '分类', width: 100, dataIndex: 'category' },
    { title: '品牌', width: 100, dataIndex: 'brand' },
    { title: '图片', width: 200, dataIndex: 'img1', render: (text) => <Image src={text} width={80} height={80} /> },
    { title: '原价', width: 100, dataIndex: 'originprice' },
    { title: '折扣', width: 100, dataIndex: 'discount' },
    { title: '销量', width: 100, dataIndex: 'sales' },
    { title: '库存', width: 100, dataIndex: 'stock' },
    {
      title: '是否推荐',
      width: 110,
      fixed: 'right',
      dataIndex: 'isrecommend',
      render: (text, record) => (
        <Switch
          checked={text}
          onChange={() => {
            changeRecommendFlag(record.proid, text);
          }}
        />
      )
    }
  ];

  return (
    <div>
      <Table columns={columns} dataSource={proList} rowKey={(record) => record.proid} scroll={{ x: 1500, y: 740 }}></Table>
    </div>
  );
}

export default Index;
